package com.lh_travel.lohas.base;

import android.util.Log;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by aaron on 2018/5/31.
 */

public class EncryptInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();

        String encode = "";

        if (request.method().equals("POST")) {

            if (request.body() instanceof FormBody) {
                FormBody.Builder bodyBuilder = new FormBody.Builder();
                FormBody formBody = (FormBody) request.body();

                //取出原有的参数
                for (int i = 0; i < formBody.size(); i++) {

                    encode = encode + formBody.encodedName(i) + "=" + formBody.encodedValue(i) + "&";

                    bodyBuilder.addEncoded(formBody.encodedName(i), formBody.encodedValue(i));

                }

                encode = encode.substring(0, encode.length() - 1);

                //md5加密
                String sign = md5(encode);

                //重组formbody,
                bodyBuilder.addEncoded("sign", sign);

                formBody = bodyBuilder.build();

                Request build = request.newBuilder().post(formBody).build();

                return chain.proceed(build);
            }
        }

        return chain.proceed(request);
    }

    /**
     * 生成32位md5码
     *
     * @param password
     * @return
     */
    public static String md5(String password) {

        try {
            // 得到一个信息摘要器
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] result = digest.digest(password.getBytes());
            StringBuffer buffer = new StringBuffer();
            // 把每一个byte 做一个与运算 0xff;
            for (byte b : result) {
                // 与运算
                int number = b & 0xff;// 加盐
                String str = Integer.toHexString(number);
                if (str.length() == 1) {
                    buffer.append("0");
                }
                buffer.append(str);
            }

            // 标准的md5加密后的结果
            return buffer.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }

    }
}
